<?php

namespace app\auth;

use app\libs\Application;
use app\models\Platform;
use app\traits\ErrorCode;

class PlatformAuth
{
    use ErrorCode;

    public function auth()
    {
        $request = Application::$app->request;
        $platformId = $request->getPost('platform_id');
        $authToken = $request->getPost('auth_token');
        $authTime = $request->getPost('auth_time');
        $appId = $request->getPost('app_id');
        if (empty($platformId)) {
            self::$errorCode = ERROR_PLATFORM_ID_PARAM_EMPTY;
            return false;
        }
        if (empty($authToken)) {
            self::$errorCode = ERROR_AUTH_TOKEN_PARAM_EMPTY;
            return false;
        }
        if (empty($authTime)) {
            self::$errorCode = ERROR_AUTH_TIME_PARAM_EMPTY;
            return false;
        }
        if (empty($appId)) {
            self::$errorCode = ERROR_APP_ID_PARAM_EMPTY;
            return false;
        }
        //当前时间
        $time = time();
        if (($authTime+60) < $time) {
            self::$errorCode = ERROR_AUTH_TIME_OUT;
            return false;
        }
        return self::verifyAuthToken($platformId, $authToken, $authTime);
    }

    public static function verifyAuthToken($plaformId, $authToken, $authTime, $authType = 1)
    {
        $model = Platform::findFirst([
           'conditions' => 'open_id=?0 and status = 1',
            'limit' => 1,
            'columns' => 'token,auth_type',
            'bind' => [$plaformId]
        ]);
        if (!$model) {
            self::$errorCode = ERROR_PLATFORM_NOT_EXISTS;
            return false;
        }
        $genToken = md5($model->token . $authTime);
        if ($genToken != $authToken) {
            self::$errorCode = ERROR_PLATFORM_ACCESS_AUTH_FAILED;
            return false;
        }
        return true;
    }
}